const express = require('express');
const app = express();
const fs = require('fs');
const ejs = require('ejs');

app.use(express.static('.'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const delay = require('delay');

const formidable = require('formidable');

async function render(file, data = {}) {
    try {
        //文件缓存
        let path = __dirname + '/view/' + file;
        let str = await fs.promises.readFile(path, { encoding: 'utf8' });
        let html = ejs.render(str, data);
        return html;
    } catch (err) {
        console.error(err);
        return '';
    }
}

async function upload(req) {
    return new Promise((resolve, reject) => {
        const form = formidable({ multiples: false });
        form.parse(req, (err, fields, files) => {
            if (err) {
                console.error(err);
                resolve([]);
                return;
            } else {
                resolve([fields, files]);
            }
        });
    });
}

async function file_exists(file) {
    try {
        await fs.promises.stat(file);
        return true;
    } catch (err) {
        // console.log(err);
        return false;
    }
}

async function unlink(file) {
    let isExist = await file_exists(file);
    if (!isExist) return true;

    try {
        await fs.promises.unlink(file);
        return true;
    } catch (err) {
        console.log(err);
        return false;
    }
}

// app.all('/', async function (req, res) {
//     if (req.method == 'POST') {
//         // let data = req.body;
//         // console.log(data);

//         let [fields, files] = await upload(req);

//         console.log(fields, Object.keys(files));

//         res.json({
//             status: true,
//         });
//         return;
//     }

//     res.send(await render('index.html', {}));
// });

app.all('/', async function (req, res) {
    if (req.method == 'POST') {
        let data = req.body;
        console.log(data);



        res.json({
            status: true,
        });
        return;
    }

    // console.log(await file_exists('uploads/Mac35.jpg'));

    res.send(await render('index.html', {}));
});

app.get('/test', async function (req, res) {
    res.send(await render('test.html', {}));
});

app.post('/upload', async function (req, res) {
    let domain = '/uploads/';
    let dst = __dirname + '/uploads/';
    try {
        let [fields, files] = await upload(req);

        let file = files['thumb'];

        // console.log(file);
        await fs.promises.copyFile(file.filepath, dst + file.originalFilename);

        res.json({ code: 0, msg: '上传成功！', url: domain + file.originalFilename });
    } catch (err) {
        console.log(err);

        res.json({ code: 1, msg: '上传失败！', url: '' });
    }
});

app.post('/upload2', async function (req, res) {
    let domain = '/uploads/';
    let dst = __dirname + '/uploads/';
    try {
        let [{ name, total, index, fileSize }, files] = await upload(req);

        let file = files['data'];
        // console.log(file);


        if (index == 1) {
            await unlink(dst + name);
            await unlink(dst + name + '.tmp');
        }

        let content = await fs.promises.readFile(file.filepath);
        await fs.promises.appendFile(dst + name + '.tmp', content);

        if (index == total) {
            await fs.promises.rename(dst + name + '.tmp', dst + name);
        }

        await delay(200);

        res.json({ status: true, percent: Math.round(index / total * 100), msg: '上传成功！', url: domain + name });
    } catch (err) {
        console.log(err);

        res.json({ status: false, percent: Math.round(index / total * 100), msg: '上传失败！', url: domain + name });
    }
});


app.use(function (err, req, res, next) {
    res.status(500).send(err.name);
});

app.listen(3000);
